//
//  Login.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/4/9.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SwiftyJSON

class Login: HMViewController, UITextFieldDelegate {
    // MARK: - 变量
    
    // 遮罩view
    var _maskView: UIView?
    // MARK: - 常量
    let bgImg = UIImageView()
    let logo = UIImageView()
    let photoField = UITextField()
    let smsField = UITextField()
    let smsButton = UIButton()
    let loginButton = UIButton()
    let registerButton = UIButton()
    let bindingButton = UIButton()
    // 线条
    let line = UIView()
    let line1 = UIView()
    let lineVertical = UIView() //竖线
    // 登录方式
    let weiBoLogin = UIButton()
    let weChatLogin = UIButton()
    let qqLogin = UIButton()
    /// 状态栏(statusbar)
    let statusRect = UIApplication.shared.statusBarFrame
    /// 标题栏
    let navARect = UINavigationBar.appearance().frame
    
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "登录界面"
        self.view.backgroundColor = UIColor.white
        self.isHideNavigationBar = true
        UserDefaults.standard.set(1, forKey: "hm_role") // 默认是普通用户
        keyBordNotification(this: self, aShow: #selector(keyBoardWillShow(_:)), aHide: #selector(keyBoardWillHide(_:)))
    }
    
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
         IQKeyboardManager.shared.enable = true
//
        if UserDefaults.standard.string(forKey: "hm_smsCode") != nil  &&  UserDefaults.standard.string(forKey: "hm_telNum") != nil {
          self.smsField.text = UserDefaults.standard.string(forKey: "hm_smsCode")
          self.photoField.text = UserDefaults.standard.string(forKey: "hm_telNum")
          self.setButtonSytle()
        }
       
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    // MARK: - 配置view
    override func setupView() {

        _maskView = UIView.createMaskView(this: self, action: #selector(onMark))

        view.addSubview(bgImg)
        view.addSubview(bindingButton)
        view.addSubview(registerButton)
        view.addSubview(logo)
        view.addSubview(photoField)
        view.addSubview(line)
        view.addSubview(smsField)
        view.addSubview(lineVertical)
        view.addSubview(smsButton)
        view.addSubview(line1)
        view.addSubview(loginButton)
        view.addSubview(weChatLogin)
        view.addSubview(weiBoLogin)
        view.addSubview(qqLogin)


        bgImg.image = UIImage.init(named: "bg.png")
        let heightStr = statusRect.height
        let _str = "\(heightStr)"
        bgImg.centerYAlign(view: view, predicate: _str)
        bgImg.centerXAlign(view: view)
        bgImg.width(view: view)


        bindingButton.topAlign(view: view, predicate: "30")
        bindingButton.leadingAlign(view: view, predicate: "20")
        bindingButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        bindingButton.setTitle("更改绑定", for: .normal)   //titleLabel?.text = "更改绑定"
        bindingButton.addTarget(self, action: #selector(bindingClick), for: .touchUpInside)

        registerButton.topAlign(view: view, predicate: "30")
        registerButton.trailingAlign(view: view, predicate: "-20")
        registerButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        registerButton.setTitle("注册", for: .normal)
        registerButton.addTarget(self, action: #selector(registerClick), for: .touchUpInside)


        logo.centerXAlign(view: view)
        logo.topAlign(view: view, predicate: "100")
        logo.imgName(name: "logo.png")

        photoField.topVertically(view: logo, predicate: "20")
        photoField.leadingAlign(view: view, predicate: "60")
        photoField.trailingAlign(view: view, predicate: "-60")
        photoField.heightConstrain(predicate: "44")
        photoField.tag = 102
        photoField.placeholder = "手机号"
        photoField.delegate = self
        photoField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        photoField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")


        line.topVertically(view: photoField, predicate: "0")
        line.leadingAlign(view: view, predicate: "60")
        line.trailingAlign(view: view, predicate: "-60")
        line.backgroundColor = UIColor.gray
        line.heightConstrain(predicate: "2")


        smsField.topVertically(view: line, predicate: "10")
        smsField.leadingAlign(view: view, predicate: "60")
        smsField.trailingAlign(view: view, predicate: "-60")
        smsField.heightConstrain(predicate: "44")
        smsField.tag = 101
        smsField.placeholder = "验证码"
        smsField.delegate = self
        smsField.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        smsField.setValue(UIColor.gray, forKeyPath: "_placeholderLabel.textColor")


        smsButton.topVertically(view: line, predicate: "10")
        smsButton.trailingAlign(view: smsField, predicate: "0")
        smsButton.heightConstrain(predicate: "44")
        smsButton.widthConstrain(predicate: "100")
        smsButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        smsButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        smsButton.setTitle("获取验证码", for: .normal)
        smsButton.addTarget(self, action: #selector(getCodeVerifying(sender:)), for: .touchUpInside)



        lineVertical.topVertically(view: line, predicate: "10")
        lineVertical.leadingAlign(view: smsButton, predicate: "0")
        lineVertical.heightConstrain(predicate: "42")
        lineVertical.backgroundColor = UIColor.gray
        lineVertical.widthConstrain(predicate: "2")


        line1.topVertically(view: smsField, predicate: "0")
        line1.leadingAlign(view: view, predicate: "60")
        line1.trailingAlign(view: view, predicate: "-60")
        line1.backgroundColor = UIColor.gray
        line1.heightConstrain(predicate: "2")

        loginButton.topVertically(view: line1, predicate: "40")
        loginButton.leadingAlign(view: view, predicate: "60")
        loginButton.trailingAlign(view: view, predicate: "-60")
        loginButton.backgroundColor =  UIColor.RGBA(r: 180, g: 180, b: 180, a: 1)  //configure.shareConfigure.HMColor1
        loginButton.heightConstrain(predicate: "44")
        loginButton.isEnabled = false
        loginButton.setTitle("登录", for: .normal)
        loginButton.setTitleColor(UIColor.white, for: .normal)
        loginButton.addTarget(self, action: #selector(loginClick), for: .touchUpInside)
        loginButton.layer.cornerRadius = 20


        weChatLogin.topVertically(view: loginButton, predicate: "50")
        weChatLogin.centerXAlign(view: view)
        weChatLogin.heightConstrain(predicate: "90")
        weChatLogin.setImage(UIImage(named: "weChat.png"), for: .normal)
        weChatLogin.setTitle("微信登录", for: .normal)
        weChatLogin.setTitleColor(UIColor.black, for: .normal)
        weChatLogin.addTarget(self, action: #selector(weChatClick), for: .touchUpInside)
        weChatLogin.widthConstrain(predicate: "80")
        let weChatImg: CGSize = (weChatLogin.imageView?.bounds.size)!
        weChatLogin.imageEdgeInsets = UIEdgeInsetsMake(-5, 8, 10, 0)
        weChatLogin.titleEdgeInsets = UIEdgeInsetsMake(weChatImg.height + 10, -weChatImg.width, 0, 0)
        weChatLogin.titleLabel?.font = UIFont.systemFont(ofSize: 13)



        weiBoLogin.topVertically(view: loginButton, predicate: "50")
        weiBoLogin.leadingAlign(view: weChatLogin, predicate: "100")
//        weiBoLogin.trailingAlign(view: weChatLogin, predicate: "-40")
        weiBoLogin.heightConstrain(predicate: "90")
        weiBoLogin.setImage(UIImage(named: "weiBo.png"), for: .normal)
        weiBoLogin.setTitle("微博登录", for: .normal)
        weiBoLogin.setTitleColor(UIColor.black, for: .normal)
        weiBoLogin.widthConstrain(predicate: "80")
        weiBoLogin.imageEdgeInsets = weChatLogin.imageEdgeInsets
        weiBoLogin.titleEdgeInsets = weChatLogin.titleEdgeInsets
        weiBoLogin.titleLabel?.font = weChatLogin.titleLabel?.font



        qqLogin.topVertically(view: loginButton, predicate:  "50")
        qqLogin.trailingAlign(view: weChatLogin, predicate: "-100")
        qqLogin.heightConstrain(predicate: "90")
        qqLogin.setImage(UIImage(named: "qq.png"), for: .normal)
        qqLogin.setTitleColor(UIColor.black, for: .normal)
        qqLogin.widthConstrain(predicate: "80")
        qqLogin.setTitle("QQ登录", for: .normal)
        qqLogin.imageEdgeInsets = weChatLogin.imageEdgeInsets
        qqLogin.titleEdgeInsets = weiBoLogin.titleEdgeInsets
        qqLogin.titleLabel?.font = weiBoLogin.titleLabel?.font



    }

    /**
       绑定事件
     */
    @objc func bindingClick(){
        print("更改绑定")
        let _binding = Binding()
        self.pushViewController(_binding)
    }
    /**
      注册事件
     */
    @objc func registerClick(){
        print("注册")
        let signUp = SignUp()
        signUp._signStr = "注册"
        self.pushViewController(signUp)
    }
    /**
       loginClick
     */
    @objc func loginClick() {
        
        let smsStr = smsField.text!
        let _str: String = photoField.text! as String
        
  
//
        if (String.isTelNumber(num: _str) == true) {
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "sms-code/verification", parameters: ["phone": _str,"code": smsStr, "role": configure.shareConfigure.hm_role], success: { (json) in
                
                UserDefaults.standard.set(smsStr, forKey: "hm_smsCode") // 保存验证码
                UserDefaults.standard.set(_str, forKey: "hm_telNum")    // 保存手机号
                
                if json["data"]["registered"].boolValue != false {
                    if json["data"]["user"] != JSON.null {
                        let dic = json["data"]["user"].dictionaryObject!   //.dictionaryValue
                        HMLoginParam.updateUser(dic)
                        // 获取IM 登陆信息
                        HMPlatform.getLoginSig()
                        AppDelegate.shared.switchMain(showMain: nil)
                       
                    }else {
                        RKDropdownAlert.title("温馨提醒!", message: "请重新注册！")
                    }
                }else {
                     RKDropdownAlert.title("温馨提醒!", message: "请重新注册！")
                }
               
            }, fail: { (error, msg) in
//                print("------------ \(error), \(msg)")
                RKDropdownAlert.title("温馨提醒!", message: "\(msg)")
            }) { }
        }else {
             RKDropdownAlert.title("温馨提醒!", message: "请输入正确手机格式！")
        }

        
    }
    
    /**
       weChatClick
     */
    @objc func weChatClick() {
        print("weChatClick")
    }
    
    /**
     获取验证码
     */
    @objc func getCodeVerifying(sender: UIButton){
    
        let photoStr = self.photoField.text!
        sender.countdownButton(second: 60, title: "获取验证码")
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "sms-code/send", parameters: ["phone": photoStr], success: { (json) in
             self.showToast(message: "发送成功")
        }, fail: { (error, msg) in
//             print("------------ \(error)")
        }) { }
        
    }
    
    // UITapGestureRecognizer
    @objc func onMark(send: UITapGestureRecognizer) {
        _maskView?.removeFromSuperview()
        self.smsField.resignFirstResponder()//结束编辑状态
        self.photoField.resignFirstResponder()//结束编辑状态
    }
    
    // 设置按钮表现效果
    func setButtonSytle()  {
        //判断是否开启按钮
        if (self.smsField.text!.count > 0 && self.photoField.text!.count > 0) {
            openButtonRecognition(setStyleBtn: self.loginButton, isOpen: true)
        }else {
            openButtonRecognition(setStyleBtn: self.loginButton, isOpen: false)
        }
    }
    

    
    
    /**
       键盘监控
     */
    @objc func keyBoardWillShow(_ notification: Notification){
        self.view.window?.addSubview(_maskView!)
//        print("------->>keyBoardWillShow")
    }
    
    @objc func keyBoardWillHide(_ notification: Notification){
//        print("------->>keyBoardWillHide")
        self.setButtonSytle()
    }
    
    
    // MARK: - textField Delegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        if textField.tag == 101 {
            return (len <= 6)
        }else {
            return (len <= 11)
        }
    }
    
     // 点键盘按钮
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 102 {
            self.smsField.becomeFirstResponder()
        }else {
            
        }
        return true
    }
}



